package io.xmu.dataanalysis.data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.annotation.PostConstruct;

import io.xmu.dataanalysis.entity.Category;
import io.xmu.dataanalysis.entity.Goods;
import io.xmu.dataanalysis.entity.Shop;
import io.xmu.dataanalysis.entity.User;
import io.xmu.dataanalysis.repository.CategoryRepo;
import io.xmu.dataanalysis.repository.GoodsRepo;
import io.xmu.dataanalysis.repository.ShopRepo;
import io.xmu.dataanalysis.repository.UserRepo;
import io.xmu.dataanalysis.util.RandomUtils;

/**
 * @author lepdou 2017-02-25
 */
@Component
public class BaseDataInitialization {

  private Random random = new Random();

  @Autowired
  private ShopRepo shopRepo;
  @Autowired
  private UserRepo userRepo;
  @Autowired
  private GoodsRepo goodsRepo;
  @Autowired
  private BaseDataCache dataCache;
  @Autowired
  private CategoryRepo categoryRepo;

  private List<Shop> shops = new ArrayList<Shop>();


  @PostConstruct
  public void init() {
    initShops();
    initUser();
    initGoods();

    dataCache.init();
  }

  @Value("#{'${shops}'.split(',')}")
  private List<String> shopData;

  private void initShops() {
    if (CollectionUtils.isEmpty(shopData)) {
      return;
    }

    for (String shop : shopData) {
      shop = shop.trim();
      if (StringUtils.isEmpty(shop)) {
        continue;
      }
      String[] data = shop.split("@");
      String shopName = data[0];
      String shopPic = data[1];
      String cate = data[2];

      Category category = categoryRepo.findByName(cate);
      if (category == null) {
        Category newCate = new Category();
        newCate.setName(cate);
        category = categoryRepo.save(newCate);
      }

      Shop managedShop = shopRepo.findByName(shopName);

      if (managedShop == null) {
        Shop newShop = new Shop();
        newShop.setName(shopName);
        newShop.setPic(shopPic);
        newShop.setCateId(category.getId());
        managedShop = shopRepo.save(newShop);
      }

      shops.add(managedShop);
    }
  }


  @Value("#{'${user.xings}'.split(',')}")
  private List<String> xings;
  @Value("#{'${user.firstNames}'.split(',')}")
  private List<String> firstNames;
  @Value("#{'${user.secondNames}'.split(',')}")
  private List<String> secondNames;
  @Value("${user.maxSize}")
  private int userMaxSize;

  private void initUser() {
    long existedUserSize = userRepo.count();

    int xingSize = xings.size();
    int firstNameSize = firstNames.size();
    int secondNameSize = secondNames.size();

    int maxNames = xingSize * firstNameSize * secondNameSize;

    while (existedUserSize < userMaxSize && existedUserSize < maxNames) {
      String randomUser = xings.get(random.nextInt(xingSize)) + firstNames.get(random.nextInt(firstNameSize))
                          + secondNames.get(random.nextInt(secondNameSize));

      User managedUser = userRepo.findByName(randomUser);

      if (managedUser == null) {
        managedUser = new User();
        managedUser.setName(randomUser);
        managedUser = userRepo.save(managedUser);
        existedUserSize++;
      }
    }
  }

  @Value("#{'${goods.content}'.split(',')}")
  private List<String> goods;
  @Value("${goods.size}")
  private int goodsSize;

  private void initGoods() {
    if (CollectionUtils.isEmpty(goods)) {
      return;
    }

    long existedGoods = goodsRepo.count();

    while (existedGoods < goodsSize) {
      Goods randomGoods = randomGoods();
      String goodsName = randomGoods.getName();
      int shopId = randomShop();
      randomGoods.setShopId(shopId);

      Goods goods = goodsRepo.findByNameAndShopId(goodsName, shopId);

      if (goods == null) {
        goods = randomGoods;

        if (goodsName.contains("壶") || goodsName.contains("锅") || goodsName.contains("器") ||
            goodsName.contains("炉")) {
          goods.setPrice(200 + random.nextInt(300));
        } else if (goodsName.contains("支架") || goodsName.contains("配件")
                   || goodsName.contains("电源")) {
          goods.setPrice(20 + random.nextInt(80));
        } else if (goodsName.contains("手机")) {
          goods.setPrice(2000 + random.nextInt(1000));
        } else if (goodsName.contains("iPhone") || goodsName.contains("苹果")) {
          goods.setPrice(5000 + random.nextInt(2000));
        } else if (goodsName.contains("消毒柜")) {
          goods.setPrice(500 + random.nextInt(500));
        } else {
          goods.setPrice(100 + random.nextInt(200));
        }

        goodsRepo.save(goods);
        existedGoods++;
      }

    }

  }

  private Goods randomGoods() {
    int goodsSize = goods.size();
    String goodsStr = goods.get(random.nextInt(goodsSize));
    String[] info = goodsStr.split("#");

    if (info == null || info.length != 2) {
      return randomGoods();
    }

    Goods goods = new Goods();
    goods.setPic(info[1]);
    goods.setName(info[0]);

    return goods;
  }

  private int randomShop() {
    int shopSize = shops.size();
    return shops.get(random.nextInt(shopSize)).getId();
  }

}
